//
//  NetWorkTools.swift
//  sinaWeibo
//
//  Created by LSY on 16/1/10.
//  Copyright © 2016年 lsy. All rights reserved.
//

import AFNetworking

let dataErrorDomain = "com.baidu.data.error"
//创建一个枚举,任意类型
enum HTTPMethod:String {
    
    case POST = "POST"
    case GET = "GET"
}
//网络请求的处理层，以后的网络请求都通过这个类来进行网络数据的请求

class NetWorkTools: AFHTTPSessionManager {
    //    创建一个单例对象
    static let shareTools : NetWorkTools = {
        //    设置Base url
        let urlString = "https://api.weibo.com/"
        let url = NSURL(string: urlString)
        let tools = NetWorkTools(baseURL: url)
        //
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    //    网络请求的封装
    func requestJSONDict(method : HTTPMethod, urlString :String, parameters:[String : String]?, finished :(dict: [String : AnyObject]?, error : NSError?)->()){
        if method == HTTPMethod.POST{
            
            
            //        发送POST 的请求
            POST(urlString, parameters: parameters, progress: { (p) -> Void in
                print(p)
                }, success: { (_, result) -> Void in
                    
                    print(result)
                    //         请求的不成功的回调
                    guard let dict = result as?[String:AnyObject] else{
                        
                        //                domain
                        let myError = NSError(domain: dataErrorDomain, code: -100
                            , userInfo: [NSLocalizedDescriptionKey: "数据不合法"])
                        finished(dict: nil, error: myError)
                        
                        return
                    }
                    //            请求成功的回调
                    finished(dict: dict, error: nil)
                    
                }) { (_, error) -> Void in
                    
                    print(error)
                    finished(dict: nil, error: error)
            }
            
        }else{
            
            GET(urlString, parameters: parameters, progress: { (p) -> Void in
                print(p)
                }, success: { (_, result) -> Void in
                    
                    //       发送失败的回调
                    guard let dict = result as?[String:AnyObject] else{
                        
                        let myError = NSError(domain: dataErrorDomain, code: -100, userInfo: [NSLocalizedDescriptionKey:"数据错误"])
                        
                        finished(dict: nil, error: myError)
                        
                        return
                    }
                    
                    //        发送成功的回调
                    finished(dict: dict, error: nil)
                }, failure: { (_, error) -> Void in
                    print(error)
                    finished(dict: nil, error: error)
            })
        }
    }
}
